package com.windsea.relationshipmining.services;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Intent;
import android.database.Cursor;
import android.os.IBinder;
import android.os.Looper;
import android.text.format.Time;
import android.util.Log;

import com.windsea.relationshipmining.api.ContactApi;
import com.windsea.relationshipmining.database.DBServiceHandler;
import com.windsea.relationshipmining.database.DBUserData;
import com.windsea.relationshipmining.model.ContactList;

@SuppressLint("SimpleDateFormat")
public class ContactsService extends Service {

//	private static final String TAG = ContactsService.class.getSimpleName();
	public MyContactsUpdater updater;
	public DBUserData dbUserData;
	public boolean isRunning = false;

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		dbUserData = new DBUserData(getApplicationContext());
		updater = new MyContactsUpdater();

//		Log.d(TAG, "Created ContactsService");
	}

	@SuppressWarnings("deprecation")
	@Override
	public synchronized void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);

		// Starting the Service is only possible if it's not already running

		if (!this.isRunning) {
			updater.start();
			this.isRunning = true;
//			Log.d(TAG, "Started ContactsService");
		}

	}

	@Override
	public synchronized void onDestroy() {
		super.onDestroy();

		if (this.isRunning) {
			updater.interrupt();
			this.isRunning = false;
//			Log.d(TAG, "Destroyed ContactsService");
			updater = null; // for garbage collection
			Intent intentLogCallHis = new Intent(getApplicationContext(),
					LogCallHistory.class);
			startService(intentLogCallHis);
		}

	}

	// ////// Private-Updater Thread /////////

	class MyContactsUpdater extends Thread {

		static final long DELAY = 1000; 
		private boolean isRunning = true;

		@Override
		public void run() {

			boolean status = true;

			Time n = new Time();
			n.setToNow();
			long now = n.toMillis(false);

			DBServiceHandler sHandler = new DBServiceHandler(
					getApplicationContext());
			sHandler.open();
			Cursor LT = sHandler.getLifeTime();
			LT.moveToFirst();
			long end = Long.parseLong(LT.getString(LT
					.getColumnIndex("LifeTime")));
			LT.close();
			sHandler.close();
			if (isRunning && end > now) {
				try {
//					Log.d(TAG, "-- Updater running --");

					//
					if (status) {
						Looper.prepare();
						status = false;
					}

					ContactList contactList = new ContactApi(
							getContentResolver()).getContactList();
					Thread.currentThread();
					Thread.sleep(DELAY * 100);

					int i = 0;
					String contactID, name, phonenumber = "", phonetype = "", email, emailtype, address, addresstype, note, company, title, im, imtype, isstared;
					int hasProfilePic, hasAnniversary;
					do {
						contactID = contactList.getContacts().get(i)
								.getContactid();
						name = contactList.getContacts().get(i).getName();

						phonenumber = contactList.getContacts().get(i)
								.getPhone().get(0).getPhonenumber();
						phonetype = contactList.getContacts().get(i).getPhone()
								.get(0).getPhonetype();
						if (contactList.getContacts().get(i).getEmail().size() > 0) {
							email = contactList.getContacts().get(i).getEmail()
									.get(0).getEmail();
							emailtype = contactList.getContacts().get(i)
									.getEmail().get(0).getEmailType();
						} else {
							email = " ";
							emailtype = " ";
						}

						if (contactList.getContacts().get(i).getAddress()
								.size() > 0) {
							address = contactList.getContacts().get(i)
									.getAddress().get(0).getCity();
							addresstype = contactList.getContacts().get(i)
									.getAddress().get(0).getType();
						} else {
							address = " ";
							addresstype = " ";
						}
						if (contactList.getContacts().get(i).getNote().size() > 0) {
							note = contactList.getContacts().get(i).getNote()
									.get(0).getBytes().toString();
						} else {
							note = " ";
						}
						if (contactList.getContacts().get(i).getOrganization()
								.size() > 0) {
							company = contactList.getContacts().get(i)
									.getOrganization().get(0).getOrgName();
							title = contactList.getContacts().get(i)
									.getOrganization().get(0).getTitle();
						} else {
							company = " ";
							title = " ";
						}
						if (contactList.getContacts().get(i).getIm().size() > 0) {
							im = contactList.getContacts().get(i).getIm()
									.get(0).getImName();
							imtype = contactList.getContacts().get(i).getIm()
									.get(0).getImType();
						} else {
							im = " ";
							imtype = " ";
						}
						isstared = contactList.getContacts().get(i)
								.getIsStared();

						hasProfilePic = contactList.getContacts().get(i)
								.getHasProfilePhoto();
						hasAnniversary = contactList.getContacts().get(i)
								.getHasAnniversaryDay();
						dbUserData.open();
						dbUserData.insertContact(contactID, name,
								ContactApi.phoneNumberProcess(phonenumber),
								phonetype, email, emailtype, address,
								addresstype, note, company, title, im, imtype,
								isstared, hasProfilePic, hasAnniversary);
						dbUserData.close();
						i++;
						Thread.currentThread();
						Thread.sleep(DELAY);
					} while (i < contactList.getContacts().size());
					contactList = null;
					// Close contactDB
					dbUserData.close();

				} catch (InterruptedException e) {
					// Interrupted
					isRunning = false;
				}

			}

			// Stop this Service //
//			Log.d(TAG, "Stopped ContactsService!");
			stopSelf();

		}
	}

	public boolean isRunning() {
		return this.isRunning;
	}

}
